package com.svs.generator.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.svs.common.constant.Constants;
import com.svs.generator.domain.BizColumn;
import com.svs.generator.domain.BizTable;
import com.svs.generator.util.GenUtils;
import com.svs.generator.util.VelocityInitializer;

@Service
public class BizTableGenService {

	Logger logger = LoggerFactory.getLogger(BizTableGenService.class) ;
	
	@Autowired
	BizTableService bizTableService;
	@Autowired
	BizColumnService bizColumnService;

	public byte[] generatorCode(String name) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		BizTable table = bizTableService.selectByPrimaryKey(name);
		List<BizColumn> columns = bizColumnService.getListByTableName(name);

		generatorCode(table, columns, zip);
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();

	}

	/**
	 * 生成代码
	 * 
	 * @param table
	 * @param columns
	 * @param zip
	 */
	private void generatorCode(BizTable table, List<BizColumn> columns, ZipOutputStream zip) {
		VelocityInitializer.initVelocity();
		table.setColumns(columns);
		String packageName = table.getPackageName() ;
		String moduleName = GenUtils.getModuleName(packageName);
		
		VelocityContext context = GenUtils.getVelocityContext(table);
		// 获取模板列表
		List<String> templates = GenUtils.getNewTemplates();
		for (String template : templates) {
			// 渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(template, Constants.UTF8);
			tpl.merge(context, sw);
			try {
				// 添加到zip
				zip.putNextEntry(new ZipEntry(GenUtils.getNewFileName(template, table, moduleName)));
				IOUtils.write(sw.toString(), zip, Constants.UTF8);
				IOUtils.closeQuietly(sw);
				zip.closeEntry();
			} catch (IOException e) {
				logger.error("渲染模板失败，表名：" + table.getName(), e);
			}
		}
		
	}

}
